
This section tries to explain how to develop code for the application in order to facilitate the learning of the application 
to new developers. We will focus especially on the most interesting parts of the Android application like maps, GPS and camera.

\subsection{Code structure}
To develop this application we follow the view-controller model. This structure is clearly visible in the code:
\begin{enumerate}
  \item Model: The model's class is located in \emph{com.model}.
  \item View: All the interfaces in Android are programmed in XML and they are located in /res/layout.
  \item Controller: In this project we have one file for each Android's Activity. They are located in the package 
	\emph{com.fflandroid}. Also the packages \emph{fflocation.maps}, \emph{fflocation.camera} and \emph{fflocation.gps} 
	contain class to use mobile phone's camera, map and GPS.
\end{enumerate}

To establish the communication with the server we use the class \emph{ToServer} which is to the package \emph{com.web\_services}.
We have also the package \emph{com.events} to allow all the application's events.
 
\subsection{Android's activities}
Android activities have control over the interfaces XML. Each screen in the program has an Activity. In the application are 
found 10 different Activities which are located in the package \emph{com.fflandroid}:
\begin{enumerate}
 \item Login: This Activity allows users to login. It takes the name and password from the user and sends them to the server. 
 \item Register: This Activity allows users to register. It takes the information from the user and sends them to the server.
 \item Map: This is the application's main Activity. It will be explained deeply in \emph{Section 
	\ref{sectionMapAndroidImplementation}}
 \item FindFriend: Is responsible for reading friend search form and make a request to the server.
 \item ListFriends: The results of the last activity are shown in this Activity.
 \item FriendRequest: Shows all the friend requests.
 \item ModifyUser: It is the responsible for making an update with the new information about the user. 
 \item PhotoGallery: This Activity controls the notes gallery. It will be explained in \emph{Section 
      \ref{sectionGalleryAndroidImplementation}}.
 \item CreateComment: It is responsible for sending the comment to the server.
 \item CameraAndroid: This Activity controls the action of taking a photo, writing a comment and sending it to the server.
\end{enumerate}

First of all, in order to add a new Activity to the program it is necessary to modify the AndroidManifest.xml file, you can 
find a complete reference about how to program Activities in the bibliography \emph{\cite{activityReference}}.

\begin{lstlisting}[captionpos=b,label=listingActivity, caption={\textit{Activity in AndroidManifest.xml}},
language=XML, basicstyle=\small, frame=single]
<activity android:name=".Login"
 android:label="@string/app_name">
 <intent-filter>
  <action android:name="android.intent.action.MAIN" />
  <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
</activity>
\end{lstlisting}

For the main activity you have to fill at least the next items as it can be seen in \emph{Listing \ref{listingActivity}}:
\begin{enumerate}
 \item android:name: The name of the class that implements the activity, this class has to be located in 
      \emph{package="com.fflandroid"} as we have to indicate it in the \emph{AndroidManifest.xml}.
 \item android:label: The label is displayed on screen when the activity must be represented to the user. These labels are 
      defined in the file \emph{strings.xml}, but instead of using this file, you can define the label directly as 
      \emph{android:label="Login"}.
 \item intent-filter: Specifies the types of intents that an activity receiver can respond. Here is specified that he should 
      start as a \emph{Main} entry point and be into category \emph{Launcher}. This is necessary only in the main activity. 
      You can get read information about \emph{intent-filter} in the reference \cite{filterelementReference}.
\end{enumerate}

Once the activity has been added in the \emph{AndroidManifest.xml} file, the Java class, that implements Activity, can be created.
 
To change Activities you have to write the code below in \emph{Listing \ref{startActivity}}. 

\begin{lstlisting}[captionpos=b,label=startActivity, caption={\textit{Launch an Activity}},language=Java, 
basicstyle=\small, frame=single]
//Finalize the current Activity.
this.finish();
	   
//Create the new intent.
Intent newIntent = new Intent(this, CameraAndroid.class);
				
//Start the new Activity.
this.startActivityForResult(newIntent, 0);
\end{lstlisting}

All Activities have to launch this interface. The interfaces will be explained in \emph{Section 
\ref{sectionInterfacesAndroidImplementation}}. To do this task the Activities have to call \emph{setContentView(layout)}. 

In \emph{Listing \ref{exampleActivity}} you can see an example of an Activity code. This example implements \emph{OnClickListener} 
which is very common in the application Activities. The method \emph{onCreate} is called when the activity is created, here you 
can fix the interface elements to local variables, as seen in the example with \emph{buttonExample}.  In the example is also shown  
how to recognize when the user clicks in \emph{buttonExample}.

\begin{lstlisting}[captionpos=b,label=exampleActivity, caption={\textit{Example of an Activity.}},language=Java, 
basicstyle=\small, frame=single]
public class ExampleAc extends Activity 
implements OnClickListener{
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Launch the interface
    setContentView(R.layout.ExampleActivity);

    //Set the button to a local variable
    buttonExample = (Button)findViewById(R.id.butEx);
    buttonExample.setOnClickListener(this);
  }
  @Override
  public void onClick(View v) {
    //Know what is the pressed button
    Button sourceButton=(Button)v;

    //If the user press the button
    if(sourceButton==this.buttonExample){...}
    else ...
  }
}
\end{lstlisting}

\subsection{Maps}
\label{sectionMapAndroidImplementation}
This section explains how the maps are implemented in the application. So as to allow the application to access the map, the 
\emph{AndroidManifest.xml} has to be modified with this line \emph{\textless uses-permission android:name= \newline 
"android.permission.INTERNET"/\textgreater} so as to give Internet access permission to the application and \emph{\textless 
uses-library android:name="com.google.android.maps" /\textgreater} so as to provide access to maps.

\subsubsection{Map activity}
Map Activity is the main Activity in the application. It is responsible for:
\begin{enumerate}
 \item Painting all the users on a map.
 \item Recognising when a user selects a friend.
 \item Displaying the selected user's notes on the map.
 \item Recognising when the user selects a note of a groups of notes.
 \item Starting the GPS.
 \item Creating the menu.
\end{enumerate}

So the Map Activity has an object \emph{MapViewer} which deals with the map and listens for \emph{NoteSelectedEvent} events 
that are released when the user selects a group of notes. When the Activity receives an event \emph{NoteSelectedEvent}, it 
inflates the \emph{NotesGallery} Activity to display the notes. So as the Map Activity to create the menu it is necessary to 
override the method \emph{onCreateOptionsMenu()} and \emph{onOptionsItemSelected()}, in first method we inflate the menu and 
in second we get the user's selection. The menu provides access to the Activities \emph{FindFriend, CreateComment, 
FriendRequest, CameraAndroid, ModifyUser} and also to \emph{logout}.

\subsubsection{MapViewer}
This class is responsible for initializing the \emph{MapView} from Google Maps and is located in the package \emph{com.maps}. 
In this class we set the parameters of the map like zoom, key, level of zoom and so on. This class has control over the 
\emph{Overlay} that has to be painted on the map. This class has two object \emph{Overlay} which are 
\emph{overlay\_users (MapUsersOverlay)} and \emph{overlay\_notes (MapNotesOverlay)} which are responsible to paint the users 
and notes on the map. The \emph{MapViewer} listens when the user selects a friend and changes this \emph{MapUsersOverlay} for 
the \emph{MapNotesOverlay} appropriately.

\subsubsection{MapUsersOverlay}
This class has to paint the users in their correct locations. There are 2 different kind of icons. The first one is a green 
bubble which represents the logged in user and the other is a red bubble which represents his friends. All icons have also a 
shadow. This class has three main methods:
\begin{enumerate}
 \item drawMapLocations: This method translates the positions of all friends and the user to map coordinates and paints them on 
      the map by call \emph{drawNickWindow} for each user.
 \item drawNickWindow: This method paints the nick of the users on the map, for this aim, the system paints a grey rectangle on the 
      map, with the user name, right up the user icon.  
 \item getClickLocation: This method calculates the area occupied by the users icons on the screen and compares them with the 
      location of the click. If they match, then a user has been selected.
\end{enumerate}

This class extends \emph{Overlay},so the method \emph{draw} has to be overridden, which will be called whenever the user interacts 
with the map, so we have to ensure that this method calls \emph{drawMapLocations} with updated positions. Also the method 
\emph{onTap} has to be overridden, which will be called whenever the user clicks on the screen. This method calls
\emph{getClickLocation} to check if the user has selected a friend and sends an event to inform about it.

\subsubsection{MapNotesOverlay}
This class has to paint the user's notes in the correct locations. There  are 3 different kind of icons. The first, is for 
representing one single note without photo, the second for representing a single note with photo, and the last one for 
representing groups of notes. This class has four main methods:
\begin{enumerate}
 \item drawMapLocations: This method translates the positions of all notes to screen coordinates, paints them on the map 
    and calls \emph{drawMessageWindow} for each note.
 \item drawMessageWindow: This method paints the message of the notes on the map, for this aim, the system paints a grey 
    rectangle on the map, with the text, right up the note icon.  
 \item getClickLocation: This method calculates the area occupied by the notes icons on the screen considering that the 
    icons may have different size and compares them with the location of the click. If they match, a note or a group of notes
    is selected.
  \item clasifyNotes: This method is called by \emph{draw} each time that the user interacts with the map, depending on the 
    screens's zoom, we classify existing groups into new groups.
\end{enumerate}

This class extends \emph{Overlay}, so the \emph{draw} method has to be overridden, which will be called whenever the user 
interacts with the map, so we have to ensure that this method calls \emph{drawMapLocations} with updated positions. Also the 
\emph{onTap} method has to be overridden, which will be called whenever the user clicks on the screen. So this method calls
\emph{getClickLocation} to check if the user has selected a note or a group of notes, in this case this method sends an event 
to inform about it.

\subsection{GPS}
The GPS is used to update the user's position and to store the position of the created notes and photos. As before, permissions 
have to be given to the application in order to access the phone's GPS. For this reason it is necessary to modify 
\emph{AndroidManifest.xml} with the next line \emph{\textless uses-permission android:name="android.permission.GPS"/\textgreater}.
To use GPS two main classes must be known: 
\begin{enumerate}
 \item LocationManager: This class provides access to the system location services. 
 \item LocationListener: Used for receiving notifications from the \emph{LocationManager} when the location has changed. It was 
  decided to create the class \emph{GPSListener} that implements this class to allow the application to update its position in 
  the server automatically when the user changes his position (using the method \emph{onLocationChanged}). You can find this 
  class in package \emph{com.gps}.
\end{enumerate}
The GPS is activated for two different actions in the application. The first is to update the user's position, which must be 
every 200 meters in order to not overload the server. The second is when the user takes a photo, this photo has to be placed in 
the current position without this 200 meters margin. Here is an example how to activate GPS in \emph{Listing \ref{exampleGPS}}. 
To activate updates the method \emph{requestLocationUpdates(provider,minTime, minDistance, LocationListener)} must be called. 

\begin{lstlisting}[captionpos=b,label=exampleGPS, caption={\textit{Activate GPS}},language=Java, basicstyle=\small, frame=single]
//Activate the GPS
LocationManager locManag =(LocationManager) 
getSystemService(Context.LOCATION_SERVICE); 

GPSListener locationListener = new GPSListener(this); 

locManag.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
0, 200,locationListener);			        			
\end{lstlisting}

\subsection{Notes gallery}
\label{sectionGalleryAndroidImplementation}
To show the notes we use the class Gallery which is a View, and is commonly used to display items in a horizontally scrolling 
list that locks the current selection at the center. An interface was created so as to display the photos and comments in the 
same screen. Notes are loaded from the selected group in the gallery through the class \emph{ImageAdapter}, and if a note does 
not have photo, an icon which represents a note is put in the gallery.

\subsection{Camera}
To use the Camera, you must give to application a special permission in the manifiest file which is 
\emph{\textless uses-permission android:name=\newline"android.permission.CAMERA"/\textgreater}. The Activity which controls the action 
of taking a photo from the camera and sending it to the server is called \emph{CameraAndroid}. This Class has an object from 
the class \emph{CameraPreview} which provides a drawing surface with the video taken from camera and controls the initialization 
and releases the camera. When the user presses the button \emph{Take photo} the image is stored in a local variable. When the 
user presses the \emph{Save} button, the position is taken from the GPS as it was explained before in \emph{Listing 
\ref{exampleGPS}}, with the difference that this time the parameter \emph{minDistance} of the function 
\emph{requestLocationUpdates} has value "0" to ensure that current coordinates are taken with high precision. 

\subsection{Interfaces}
\label{sectionInterfacesAndroidImplementation}
As we said before all the interfaces of the program are implemented using XML. Most of the layouts of our application have 
\emph{RelativeLayout} to make the interface look the same on any phone. In the \emph{Listing \ref{exampleXML}} is shown an example
with the three interface elements who are most used in the application's layouts in a \emph{RelativeLayout}: 
\emph{TextView} for labels, \emph{EditText} for text boxes and \emph{Button} for buttons. 

\begin{lstlisting}[captionpos=b,label=exampleXML, caption={\textit{Example of some interface elements.}},language=Java, 
basicstyle=\small, frame=single]
<TextView android:id="@+id/createcomment_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Comment:"/>
		
<EditText
android:id="@+id/addcomment_comment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/createcomment_label"
android:layout_alignParentTop="true"/>
	
<Button
android:id="@+id/addcomment_ok"
android:layout_below="@id/addcomment_comment"
android:layout_alignRight="@id/addcomment_comment"
android:text="OK" />
\end{lstlisting}

\subsection{Serialization with KSoap2}
In this part will be explained how the \emph{KvmSerializable} interface was implemented. Every class which needs to be 
serialized or deserialized must implement this interface in order to be usable for the \emph{KSoap2} library. The \emph{KAuth} 
object is used so as to explain all the methods that the interface has.

First of all, the library needs to know the number of fields that the object contains. In this case the object has two 
attributes. In the following code this is what this function will return:

\begin{lstlisting}[captionpos=b,label=, caption={\textit{Activity in AndroidManifest.xml}},language=XML, basicstyle=\small, 
frame=single]
public int getPropertyCount() {
  return 2;
}
\end{lstlisting}

After knowing the number of arguments, the library needs to recognise the name and the type of each variable. To get these 
information the next method was implemented as shown in \emph{Listing \ref{getPropertyInfoClass}}.

\begin{lstlisting}[captionpos=b,label=getPropertyInfoClass, caption={\textit{Activity in AndroidManifest.xml}},language=XML, 
basicstyle=\small, frame=single]
public void getPropertyInfo(int arg0, 
    @SuppressWarnings("rawtypes") Hashtable arg1, 
	PropertyInfo arg2) {
  switch(arg0){
    case 0:
      arg2.type=PropertyInfo.INTEGER_CLASS;
      arg2.name="session";
      break;
    case 1:
      arg2.type=PropertyInfo.INTEGER_CLASS;
      arg2.name="userID";
      break;
  }
}
\end{lstlisting}

When the library serializes the object, it needs to read every field in the object. For this reason we implement this method 
which returns the object fields by value, as shown in \emph{Listing \ref{getPropertClass}}.

\begin{lstlisting}[captionpos=b,label=getPropertClass, caption={\textit{Activity in AndroidManifest.xml}},language=XML, 
basicstyle=\small, frame=single]
public Object getProperty(int arg0) {
  switch(arg0){
  case 0:
    return this.getSession();
  case 1:
    return this.getUserID();
  }
  return null;
}
\end{lstlisting}

Finally, when the library deserializes an object needs to set all its fields. Each field has an index and the values are given 
as strings. So we have to implement, in each case, how to recover the original value from the string value as shown in 
\emph{Listing \ref{setPropertyClass}}.

\begin{lstlisting}[captionpos=b,label=setPropertyClass, caption={\textit{Activity in AndroidManifest.xml}},language=XML, 
basicstyle=\small, frame=single]
public void setProperty(int arg0, Object arg1) {
  switch(arg0){
  case 0:
    this.setSession(Integer.parseInt(arg1.toString()));
    break;
  case 1:
    this.setUserID(Integer.parseInt(arg1.toString()));
    break;
  }
}
\end{lstlisting}

Obviously it is very important to make the attribute index match in all the methods because this is how they are identified 
by the library.

\subsection{Consuming web services}
In this section we are going to show how web services are consumed. This is how the \emph{ToServer} adapter class is implemented. 
We are going to create an envelope with a request inside it and then we will send it. Then we are going to get the envelope with 
the response attached in it, so we will know what the web service returned. First of all so as to create the request, we have to 
call it with the right workspace and method name. Optionally if parameters are required they are going to be added to the request 
as you can see with the \emph{KAuth} object in the code below (\emph{Listing \ref{soaprequestmethod}}).

\begin{lstlisting}[captionpos=b,label=soaprequestmethod, caption={\textit{Activity in AndroidManifest.xml}},language=XML, 
basicstyle=\small,frame=single]
KAuth a = getAuth();
String METHOD_NAME = "myUser";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("a", a);
\end{lstlisting}

When the request is created, we need to put it into an envelope. This envelope contains transfer options, like the protocol. Also 
it has a really interesting option about mapping outgoing and incoming objects. In this method the parameter we have to send is 
the authentication object from the \emph{http://controller} package, so we add it to the envelope mapping. We also can get a 
\emph{UserInfo} object that contains a \emph{Position} object so we have to add this mapping too. In this application the 
server's returned \emph{UserInfo} class objects are mapped into our \emph{KUserInfo} class and the \emph{Position} class into 
our \emph{KPosition} class, so we add it like that, from name to object class. See \emph{Listing \ref{envelopesoap}}.

\begin{lstlisting}[captionpos=b,label=envelopesoap, caption={\textit{Activity in AndroidManifest.xml}},language=XML, 
basicstyle=\small, frame=single]
SoapSerializationEnvelope envelope = 
    new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.addMapping("http://controller","KAuth",KAuth.class);

envelope.addMapping("http://model", "UserInfo", 
    new KUserInfo().getClass());
envelope.addMapping("http://model", "Position", 
    new KPosition().getClass());
\end{lstlisting}

Now is time to invoke the method in the web service. The envelope is sent through \emph{HTTP} to the web service. After this 
call we get the response in the envelope, that as we know, is a \emph{KUserInfo} because it has been deserialized by the soap 
library. See \emph{Listing \ref{httptransport}}.

\begin{lstlisting}[captionpos=b,label=httptransport, caption={\textit{Activity in AndroidManifest.xml}},language=XML, 
basicstyle=\small, frame=single]
HttpTransportSE transport = new HttpTransportSE(URL);
transport.call(SOAP_ACTION, envelope);

KUserInfo myUser =  (KUserInfo) envelope.getResponse();
\end{lstlisting}

\subsection{Required libraries}
So as to implement this application the followings libraries were needed:

\begin{itemize}
 \item \emph{ksoap2-android}: The \emph{ksoap2-android} project provides a lightweight and efficient SOAP library for the Android 
	platform \emph{\cite{KSoap2}}.
 \item \emph{android-sdk-linux\_x86}: The Android SDK provides the tools and libraries necessary to begin developing applications 
	that run on Android-powered devices \emph{\cite{SDKAndroid}}. 
 \item \emph{FFLServerModel.jar}: This library includes the model with the correct fields to map the objects from the server.
\end{itemize}

You can find all this libraries in the folder \emph{/Code/fflandroid/RequiredLibraries}.
